#include <math.h>
#include "RotatingObject.h"

RotatingObject::RotatingObject(TextureManager * textureManager, Vertex position)
:ClosedObject(textureManager, position)
{
	rotationPoint = Vertex(position.GetPosition()+Vector2D(0,2));
}
RotatingObject::RotatingObject(TextureManager * textureManager, float textureRotation,Vertex position, Vertex rotationPoint, 
								VertexList * vertices, Material * material, float mass)
:ClosedObject(textureManager, textureRotation, position, vertices, material, mass)
{
	this->rotationPoint = Vertex(position.GetPosition()+rotationPoint.GetPosition());
}
RotatingObject::~RotatingObject()
{
	
}
void RotatingObject::DrawEntryPoint()
{
	Vector2D rPoint = rotationPoint.GetPosition();
	
	glBegin(GL_LINES);
	glVertex2f(rPoint.x-1, rPoint.y+1);
	glVertex2f(rPoint.x+1, rPoint.y-1);
	
	glVertex2f(rPoint.x+1, rPoint.y+1);
	glVertex2f(rPoint.x-1, rPoint.y-1);
	glEnd();	
}
void RotatingObject::GetHoverGroup(Mouse * mouse, VertexList * group)
{
	Vertex * left = NULL;
	Vertex * right = NULL;
	
	if(vertices)
	{
		vertices->GetHoverSegment(mouse, &left, &right);
	}
		

	if(left && right && group)
	{
		group->Add(left);
		group->Add(right);
		printf("HERE1\n");
	}
	else if((mouse->GetWorldPosition() | position.GetPosition()) < 1)
	{
		printf("HERE2\n");
		group->Add(&position);
		List<Vertex> * search = vertices->head;
		while(search)
		{
			if(search->payload)
			{
				group->Add(search->payload);
			}
			search = search->next;
		}
	}		
	else if((mouse->GetWorldPosition() | rotationPoint.GetPosition()) < 1)
	{
		group->Add(&rotationPoint);
	}
}
char * RotatingObject::GetTag()
{
	char * points = vertices->GetRelativeTag(position.GetPosition());
	char * positionTag = position.GetTag();
	char * materialName = material->name;
	char * rotationPointTag = rotationPoint.GetRelativeTag(position.GetPosition());
	char * mass = propertyMenu->GetFormContent(0);
	char * tag = (char *)malloc(strlen(points)+strlen(positionTag)+strlen(materialName)+strlen(rotationPointTag)+strlen(mass)+40);
	
	sprintf(tag, "<object,pinnedobject,%s,%.3f,%d,%s,%s,%s,%s>", materialName,textureRotation,vertices->GetLength(),points,positionTag,rotationPointTag, mass);
	delete points;
	free(mass);
	return tag;		
}
Vector2D RotatingObject::GetRotationPoint()
{
	return rotationPoint.GetPosition();
}
void RotatingObject::Rotate(float theta)
{
	float sinTheta = sin(theta);
	float cosTheta = cos(theta);
	List<Vertex> * search = vertices->head;
	
	while(search)
	{
		Vector2D vertex = search->payload->GetPosition() - GetRotationPoint();
		float newX = vertex.x * cosTheta - vertex.y * sinTheta;
		float newY = vertex.y * cosTheta + vertex.x * sinTheta;
		Vector2D newPos = Vector2D(newX, newY) + GetRotationPoint();
		search->payload->SetPosition(newPos);
		search = search->next;
	}	
	CalculatePosition();
}